package jcer.core;

import gnu.getopt.Getopt;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;

public class Server {
	static String VERSION = "jcer1.0.0";
	static Log logger = LogFactory.getLog(Server.class);

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] argv) throws Exception {
		PropertyConfigurator.configure("./conf/log4j.properties");

		// default config
		String host = "0.0.0.0";
		int port = 3261;
		int workNum = 8;
		int maxConnection = 10240;
		String taskMap = "";

		// args
		int c;
		Getopt opt = new Getopt("jcer", argv, "dvh:l:p:t:c:m:");

		while ((c = opt.getopt()) != -1) {
			switch (c) {
			case 'h':
				printUsage();
				return;
			case 'l':
				host = opt.getOptarg();
				break;
			case 'p':
				port = Integer.parseInt(opt.getOptarg());
				break;
			case 't':
				workNum = Integer.parseInt(opt.getOptarg());
				break;
			case 'c':
				maxConnection = Integer.parseInt(opt.getOptarg());
				break;
			case 'm':
				taskMap = opt.getOptarg();
				break;
			}
		}
		EventDriver driver = new EventDriver();
		driver.workNum = workNum;
		driver.maxConnection = maxConnection;

		String[] tms = taskMap.split(":");
		for (String tm : tms) {
			String[] cols = tm.split("=");
			if (cols.length == 2) {
				TaskHandler.taskMap.put(Integer.parseInt(cols[0]),
						Class.forName(cols[1]));
			}
		}

		if (TaskHandler.taskMap.size() == 0) {
			System.err.println("Server start error:TaskMap is empty\n");
			printUsage();
			return;
		}

		logger.info(String.format(
				"host=%s,port=%s,workNum=%s,maxConnection=%s", host, port,
				workNum, maxConnection));
		driver.init(host, port);
		driver.loop();
	}

	static void printUsage() {
		System.out.println(VERSION);
		System.out
				.println("-----------------------------------------------------------------------------");
		System.out
				.println("-p <num>      TCP port number to listen on (default: 3261)");
		System.out
				.println("-l <addr>     interface to listen on (default: 0.0.0.0, all addresses)");
		System.out.println("-d            run as a daemon");
		System.out
				.println("-c <num>      max simultaneous connections (default: 1024)");
		System.out
				.println("-v            verbose (print errors/warnings while in event loop)");
		System.out.println("-h            print this help and exit");
		System.out
				.println("-t <num>      number of worker thread to use (default: 4)");
		System.out
				.println("-----------------------------------------------------------------------------");
	}
}
